import React from 'react'
import { ModalStyel } from './styles'
import {  createPortal } from 'react-dom'
import { useEffect ,useRef} from 'react'

export default function MyModal(props) {

  const { visible, children, closeModal } = props
 
  //  在第一次渲染时 存好 body 原先的 overflow 
  const bodyOverflow =  useRef( window.getComputedStyle( document.body).overflow );

  useEffect(() => {
    
    if ( visible ) {
      document.body.style.overflow = 'hidden';
    }else {
      document.body.style.overflow = bodyOverflow.current;
    
    }
    
  }, [visible])

  function handleClick(event) {

    console.log('点击蒙层本身时关闭模态框，点击模态框的内容时不关闭 ', (event.currentTarget === event.target) )

    //  点击蒙层本身时关闭模态框，点击模态框的内容时不关闭
    if (event.target === event.currentTarget) {
      closeModal()
    }

  }


  const modal = (
    <ModalStyel>
      <div className="modal" onClick={handleClick}>
        { children }
      </div>
    </ModalStyel>
  )

  const _modal = createPortal( modal, document.body )


  return ( visible && _modal )
}
